<script setup>
import dayjs from 'dayjs'
import { setCustomTitle } from '@/utils/unit'
import {
  getCurrQuarter,
  getMonthStartAndEnd,
  getPreviousYearsList,
  getQuarterStartAndEnd,
  getYearStartAndEnd
} from '@/utils/date.js'
import { Toast } from 'vant'
import { computed } from 'vue'
import MButton from '@/components/MButton.vue'
import { useStatisticsFromStore } from '@/stores/statistics.js'

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  }
})
const { statistics } = useStatisticsFromStore()
const emit = defineEmits(['confirm', 'update:columns'])
const { currentYear, currentQuarter, currentMonth } = getCurrQuarter()
const tabs = ref(0)
const calendarRef = ref()

const showPopup = computed({
  get() {
    return props.show
  },
  set(val) {
    emit('update:show', val)
  }
})

const isShowCalendar = ref(false)
const thisTimeSpendRank = ref({})

let columnsDataModel = {
  years: getPreviousYearsList(2020),
  types: ['季度', '月份', '全年'],
  quarters: ['1季度', '2季度', '3季度', '4季度'],
  months: [
    '1月',
    '2月',
    '3月',
    '4月',
    '5月',
    '6月',
    '7月',
    '8月',
    '9月',
    '10月',
    '11月',
    '12月'
  ],
  all: ['12个月']
}

const columnsData = ref([])
const initColumnsData = () => {
  columnsData.value = [
    {
      values: columnsDataModel.years,
      defaultIndex: columnsDataModel.years.findIndex(
        (item) => item === currentYear
      )
    },
    {
      values: ['季度', '月份', '全年'],
      defaultIndex: 0
    },
    {
      values: ['1季度', '2季度', '3季度', '4季度'],
      defaultIndex: columnsDataModel.quarters.findIndex(
        (item) => item === currentQuarter
      )
    }
  ]
}
onMounted(() => {
  initColumnsData()
})
const onConfirmDiy = () => {
  if (!thisTimeSpendRank.value.createTimeStart) {
    Toast('请选择开始时间！')
    return
  }

  if (!thisTimeSpendRank.value.createTimeEnd) {
    Toast('请选择结束时间！')
    return
  }
  statistics.timeSpendRank.createTimeStart =
    thisTimeSpendRank.value.createTimeStart
  statistics.timeSpendRank.createTimeEnd = thisTimeSpendRank.value.createTimeEnd
  isShowCalendar.value = false
  tabs.value = 0
  emit('update:show', false)

  const timeStart = dayjs(thisTimeSpendRank.value.createTimeStart).format(
    'YYYY-MM-DD'
  )
  const timeEnd = dayjs(thisTimeSpendRank.value.createTimeEnd).format(
    'YYYY-MM-DD'
  )

  const mages = [
    `${setCustomTitle(timeStart, 4)} ${setCustomTitle(timeEnd, 4)}`
  ]
  emit('confirm', mages)
}

// 查询时间格式化
function formatDate(date) {
  return dayjs(date).format('YYYY-MM-DD')
}

//  时间选择确定
const onConfirm = (date) => {
  emit('confirm', date)
  const [a, b] = date

  if (b.indexOf('季度') !== -1) {
    const quart = b.replace('季度', '')
    const { start, end } = getQuarterStartAndEnd(a, Number(quart), dayjs)
    statistics.timeSpendRank.createTimeStart = start
    statistics.timeSpendRank.createTimeEnd = end
  }

  if (b.indexOf('月') !== -1) {
    const month = b.replace('月', '')
    const { start, end } = getMonthStartAndEnd(a, Number(month))
    statistics.timeSpendRank.createTimeStart = start
    statistics.timeSpendRank.createTimeEnd = end
  }

  if (b.indexOf('个月') !== -1) {
    const { start, end } = getYearStartAndEnd(a)
    statistics.timeSpendRank.createTimeStart = start
    statistics.timeSpendRank.createTimeEnd = end
  }
  emit('update:show', false)
}

//  获取已选时间
const selectTime = (date) => {
  const [start, end] = date
  thisTimeSpendRank.value.createTimeStart = start
    ? formatDate(start) + ' 00:00:00'
    : ''
  thisTimeSpendRank.value.createTimeEnd = end
    ? formatDate(end) + ' 23:59:59'
    : ''
}

// 选择 月份 季度 全年 显示对应数据
const onChange = (picker, value) => {
  switch (value[1]) {
    case '月份':
      columnsData.value[2].values = columnsDataModel.months
      columnsData.value[2].defaultIndex = columnsDataModel.months.findIndex(
        (item) => item === currentMonth
      )
      break
    case '季度':
      columnsData.value[2].values = columnsDataModel.quarters
      columnsData.value[2].defaultIndex = columnsDataModel.quarters.findIndex(
        (item) => item === currentQuarter
      )
      break
    case '全年':
      columnsData.value[2].values = columnsDataModel.all
      break
  }
}

// 日期选择器关闭
const onCancel = () => {
  emit('update:show', false)
}

// 日历清空事件
const resCalendarChange = () => {
  thisTimeSpendRank.value = {}
  calendarRef.value.reset()
  isShowCalendar.value = false
  emit('update:show', true)
}

watch(
  () => tabs.value,
  (val) => {
    if (val !== 0) {
      isShowCalendar.value = true
    }
  }
)
</script>

<template>
  <div>
    <van-calendar
      v-model="isShowCalendar"
      :min-date="new Date(new Date().getTime() - 365 * 24 * 60 * 60 * 1000)"
      :max-date="new Date(new Date().getTime())"
      @select="selectTime"
      class="calendar-box"
      ref="calendarRef"
      type="range"
      color="#36B374"
      @close="tabs = 0"
      @confirm="onConfirm"
    >
      <template #footer>
        <div
          class="h-65px pb-15px pt-10px px-12px w-full box-border shadow-[0_-10px_16px_0_#0000000d] bg-#FFFFFF"
        >
          <div class="flex justify-between w-full gap-10px box-border">
            <m-button m-class="w-96px h-40px" plain @click="resCalendarChange"
              >清空</m-button
            >
            <m-button m-class="w-240px h-40px" @click="onConfirmDiy">
              确定
            </m-button>
          </div>
        </div>
      </template>
    </van-calendar>

    <van-popup v-model="showPopup" round position="bottom">
      <van-picker
        show-toolbar
        :columns="columnsData"
        @change="onChange"
        @cancel="onCancel"
        @confirm="onConfirm"
      >
        <template #columns-top>
          <div class="w-full flex justify-center">
            <van-tabs
              type="card"
              v-model="tabs"
              color="#36B374"
              class="w-65% m-b12px"
            >
              <van-tab title="标准时间段"></van-tab>
              <van-tab title="自定义日期"></van-tab>
            </van-tabs>
          </div>
        </template>
      </van-picker>
    </van-popup>
  </div>
</template>

<style scoped lang="less">
:deep(.calendar-box) {
  .van-icon-cross::before {
    content: '\e65e';
  }
}
:deep(.van-calendar__footer) {
  padding: 0;
}
:deep(.van-tabs__nav--card) {
  border-radius: 4px;
  overflow: hidden;
}
</style>
